import { getToken, setToken, removeToken } from '@/utils/auth'
import http from "@/utils/request"

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userId: '',
    roleId: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLE: (state, role) => {
    state.roleId = role
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  }
}

const actions = {
  login({ commit }, res) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', res.data.token)
      commit('SET_ROLE', res.data.userInfo.role_id)
      commit('SET_USER_ID', res.data.userInfo.userId)
      setToken(res.data.token)
      resolve()
    })
  },

  // get user info
  getInfo({ commit }) {
    return new Promise((resolve, reject) => {
      http.get('/login/getMenu').then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, avatar } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken()
      commit('SET_NAME', '')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

